<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-10-14
 * Time: 上午10:45
 * @author 郑钟良<zzl@ourstu.com>
 */

namespace Question\Model;


use Think\Model;

class QuestionRecommendModel extends Model
{
    protected $tableName = 'question_recommend';
    protected $_auto = array(
        array('status', '1', self::MODEL_INSERT),
    );
    protected $insertField = 'question_id'; //新增数据时允许操作的字段
    protected $updateField = 'question_id'; //新增数据时允许操作的字段

    public function addRecommend($ids)
    {
        $arealy_ids = $this->getRecommendIds();
        $ids = array_diff($ids, $arealy_ids);
        foreach ($ids as $val) {
            $data['question_id'] = $val;
            $this->createQuestion($data);
        }
        unset($val);
        return true;
    }

    public function getRecommendIds()
    {
        $ids = $this->field('question_id')->select();
        $ids = array_column($ids, 'question_id');
        $map['id'] = array('in', $ids);
        $map['status'] = 1;
        $ids = D('Question/Question')->getIds($map);
        return $ids;
    }

    private function createQuestion($data)
    {
        $data = $this->create($data);
        if (!$data) return false;
        return $this->add($data);
    }

    public function getQuestions($num=0){
        $ids=$this->getRecommendIds();
        if($num){
            $ids=array_slice($ids,0,$num);
        }
        $questionList=array();
        foreach($ids as $val){
            $questionList[]=D('Question/Question')->getQuestion($val);
        }
        unset($val);
        return $questionList;
    }

    public function deleteRecommend($ids)
    {
        $result = $this->where(array('question_id' => array('in', $ids)))->delete();
        return $result;
    }
} 